<?php
/**
 * PHPinChains Framework
 *
 * LICENSE
 *
 * This source file is subject to the PHPinChains BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://phpinchains.synflag.com/en/pub/license.php
 *
 * @category   PHPinChains
 * @package    phpinchains
 * @copyright  Copyright (c) 2005-2009 SynFlag Online Agentur - Germany
 * @license    http://phpinchains.synflag.com/en/pub/license.php PHPinChains BSD License
 * @since Date 28.01.2006
 * @version    0.8.1
 */

// Core constants: default values
if (!defined("MODEL2_CREATE_PSP"))
    define("MODEL2_CREATE_PSP", false);
if (!defined("MODEL2_FORCE_COMPILE"))
    define("MODEL2_FORCE_COMPILE", false);
if (!defined("MODEL2_LOG_DIR"))    
    define("MODEL2_LOG_DIR", "");
if (!defined("MODEL2_DEBUG_MODE"))    
    define("MODEL2_DEBUG_MODE", false);
if (!defined("MODEL2_DB_DEBUG_MODE"))    
    define("MODEL2_DB_DEBUG_MODE", false);
if (!defined("MODEL2_ENCODING"))
    define("MODEL2_ENCODING", "ISO-8859-1");

if ( !defined('PATH_SEPARATOR') ) {
    define('PATH_SEPARATOR', ( substr(PHP_OS, 0, 3) == 'WIN' ) ? ';' : ':');
}
if ( !defined('DIRECTORY_SEPARATOR') ) {
    define('DIRECTORY_SEPARATOR', ( substr(PHP_OS, 0, 3) == 'WIN' ) ? '\\' : '/');
}


if (!function_exists('file_put_contents')) {
    function file_put_contents($file, $contents = '', $method = 'w') {
        $file_handle = fopen($file, $method);
        fwrite($file_handle, $contents);
        fclose($file_handle);
        return true;
    }
}
/*
 * c: core
 * xt: extended
 * s: sql
 * x: xml
 * cms: XICS tags
 * h: html
 * fmt: format, i18n
 * p: project (specific)
 * i: initializer
 */
// namespaces for PSPParser
$GLOBALS['MODEL2_NS'] = array (
    'c',
    'xt',
    's',
    'x',
    'ajax',
    'cms',
    'h',
    'fmt',
    'p',
    'example',
    'widget',
    'xics',
    'is' /* xics tags for output types */,
    'method' /* method in new engine */
);

// error handler for debugging
function phpinchains_error_handler($errorno, $errormsg) {
// ignore deprecated warnings
    if (preg_match('/ is deprecated$/', $errormsg))
        return;
    switch ($errorno) {
        case E_USER_ERROR:
            print "FATAL ERROR: ";
            break;
        case E_USER_WARNING:
            print "ERROR: ";
            break;
        case E_USER_NOTICE:
            print "WARNING: ";
            break;
        default:
            print "UNKNOWN ERROR: ";
            break;
    }
    $stacktrace = debug_backtrace();
    print "<b>$errormsg</b><br/><table border=\"0\">\n";
    $thiserr = array ();
    array_shift($stacktrace);
    $lasterr = array_shift($stacktrace);
    foreach ($stacktrace as $tr) {
        $thiserr = $tr;
        if (!isset ($thiserr['class'])) {
            $thiserr['class'] = '[PHP]';
        }
        if (!isset ($thiserr['function'])) {
            $thiserr['function'] = '[PHP]';
        }
        print "<tr><td>at ".$thiserr['class'].'.'.$thiserr['function'].'('.end(explode('/', $lasterr['file'])).':'.$lasterr['line'].')</td><td>'.$lasterr['file'].'</td></tr>\n';
        $lasterr = $thiserr;
    }
    if (count($stacktrace)) {
        print '<tr><td>at [PHP].main('.end(explode('/', $lasterr['file'])).':'.$lasterr['line'].')'.'</td><td>'.$lasterr['file'].'</td></tr>'."\n";
    }
    exit;
}


//set_error_handler("phpinchains_error_handler");
/*if (version_compare(phpversion(), "5.0.0", ">=") == 1) {
    set_error_handler("phpinchains_error_handler", E_ALL & ~E_NOTICE);
}*/


// import function as replacement of include_once and require_once
// TODO use ini_set as default, fake only if ini_set('include_path', ...) does not work 
function m2import($file, $silent = false) {
    if (!$file) {
        $msg = "No file given to import!\n";
        trigger_error($msg, E_USER_ERROR);
    }

    if (isset ($GLOBALS['MODEL2_BASEDIR'])) {
        if (file_exists($GLOBALS['MODEL2_BASEDIR'].$file)) {
            require_once ($GLOBALS['MODEL2_BASEDIR'].$file);
            return true;
        }
        if (file_exists($GLOBALS['MODEL2_BASEDIR'].'classes/'.$file)) {
            require_once ($GLOBALS['MODEL2_BASEDIR'].'classes/'.$file);
            return true;
        }
    }
    if ($GLOBALS['MODEL2_INCLUDE_PATH_EMULATE']) {
        if (is_array($GLOBALS['MODEL2_INCLUDE_PATH_PARTS']))
            foreach ($GLOBALS['MODEL2_INCLUDE_PATH_PARTS'] as $path) {
                if (file_exists($path.'/'.$file)) {
                    require_once ($path.'/'.$file);
                    return true;
                }
            }
        if ($silent) {
            return false;
        }
        else {
            $msg = "FILE NOT FOUND FOR IMPORT: '$file' in include path '".MODEL2_INCLUDE_PATH.':'.preg_replace('/\/$/', '', $GLOBALS['MODEL2_BASEDIR']).':'.preg_replace('/\/$/', '', $GLOBALS['MODEL2_BASEDIR']).'/classes'."'\n";
            trigger_error($msg, E_USER_ERROR);
            exit;
        }
    } else {
        if ((include_once($file)) === false) {
            if (!$silent) {
                $msg = "FILE NOT FOUND FOR IMPORT: '$file' in include path '".MODEL2_INCLUDE_PATH.':'.preg_replace('/\/$/', '', $GLOBALS['MODEL2_BASEDIR']).':'.preg_replace('/\/$/', '', $GLOBALS['MODEL2_BASEDIR']).'/classes'."'\n";
                trigger_error($msg, E_USER_ERROR);
                exit;
            }
        } else {
            return true;
        }
    }
}

// process include path to be used in m2import
if (MODEL2_INCLUDE_PATH) {
    $incpath = '.'.PATH_SEPARATOR.MODEL2_INCLUDE_PATH.PATH_SEPARATOR.dirname(__FILE__).PATH_SEPARATOR.ini_get('include_path');
    ini_set('include_path', $incpath);
    $GLOBALS['MODEL2_INCLUDE_PATH_EMULATE'] = false;
    if (ini_get('include_path') != $incpath) {
        $GLOBALS['MODEL2_INCLUDE_PATH_PARTS'] = explode(PATH_SEPARATOR, MODEL2_INCLUDE_PATH);
        $GLOBALS['MODEL2_INCLUDE_PATH_EMULATE'] = true;
        foreach ($GLOBALS['MODEL2_INCLUDE_PATH_PARTS'] as $part) {
            $part = trim($part);
            if ($part == '.')
                $part = '';
        }
    }
}

/**
 * Code from 'darkodemon at gmail dot com' found on www.php.net
 *
 * Returns an unicode character for the given code
 *
 * @param unknown_type $codes
 * @return unknown
 */
function uchr ($codes) {
    if (is_scalar($codes)) $codes= func_get_args();
    $str= '';
    foreach ($codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
    return $str;
}

if(!function_exists("newid")) {

/**
 * Code from 'dot dot dot dot dot alexander at gmail dot com' found on www.php.net
 *
 * Creates some unique id
 *
 * @param string $prefix
 * @return string
 */
    function newid($prefix = "") {
        return ($prefix . uniqid( hash("md5", time()), true ) . time() . @$_SERVER['REMOTE_ADDR']);
    }

}


m2import('phpinchains/PHPinChains.php');
m2import('phpinchains/RuntimeConfig.php');
m2import('phpinchains/ApplicationContext.php');
m2import('phpinchains/parser/psp/PSPParser.php');
m2import('phpinchains/parser/conf/ConfParser.php');
m2import('phpinchains/FilterChain.php');
m2import('env.o.inc.php');  
if (!headers_sent() && (!defined("MODEL2_NO_SESSION") || !MODEL2_NO_SESSION)) {
    if (!defined("MODEL2_SESSION_NAME"))
        define("MODEL2_SESSION_NAME", "PHPinChainsSessionId");
    session_cache_limiter('nocache');
    session_name(MODEL2_SESSION_NAME);
    session_start();
}

$GLOBALS['env'] = & env::getInstance();
$env = $GLOBALS['env'];

// XSS protection against stealing of session
if (!headers_sent() && !$env->getSession("phpinchains_session_initialized") && version_compare(phpversion(), "4.3.2", ">=") == 1) {
    session_regenerate_id(true);
    $env->setSession("phpinchains_sec_code", substr(newid(), 0, 15));
    $env->setSession("phpinchains_session_initialized", true);
}

?>